############################util/data_processor.py#################
from utils.prometheus_client import PrometheusClient
import concurrent.futures
import time
from datetime import datetime, timezone, timedelta
import datetime
# 常量定义
PROMETHEUS_URLS = {
    "216": "http://10.10.7.216:9090",
    "prod": "http://prometheus.ksherpay.com"
}

PROD_NAMESPACE = "ksher"

def format_creation_time(timestamp):
    """将时间戳格式化为北京时间字符串"""
    if not timestamp:
        return "未知"
    try:
        # 将时间戳转换为北京时间
        utc_time = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
        # 转换为北京时间 (UTC+8)
        beijing_time = utc_time.astimezone(datetime.timezone(datetime.timedelta(hours=8)))
        return beijing_time.strftime('%Y-%m-%d %H:%M:%S')
    except (ValueError, TypeError):
        return "未知"

def get_deployments_from_prod(prom: PrometheusClient, namespace: str = "ksher"):
    """从生产环境获取所有deployment名称"""
    queries = [
        f'kube_deployment_metadata{{namespace="{namespace}"}}',
        f'kube_deployment_status_replicas{{namespace="{namespace}"}}'
    ]
    deployments = {
        item.get("metric", {}).get("deployment", "")
        for q in queries
        for item in prom.query(q)
    }
    return sorted(filter(None, deployments))


def get_images_and_runtime_from_uat(prom: PrometheusClient, deployment: str):
    """从UAT环境获取镜像和创建时间，按优先级查询多个命名空间"""
    search_path = [
        {"namespace": "uat-ksher", "deployment": deployment, "suffix": ""},
        {"namespace": "uat-ksher", "deployment": f"{deployment}-uat", "suffix": "-uat"},
        {"namespace": "uat-ksher-py", "deployment": deployment, "suffix": ""},
        {"namespace": "uat-ksher-py", "deployment": f"{deployment}-uat", "suffix": "-uat"},
    ]

    for search in search_path:
        images = prom.get_images_from_env(search["deployment"], search["namespace"])
        if images != ["Not Found"]:
            # 获取创建时间
            creation_time = prom.get_deployment_creation_time(search["deployment"], search["namespace"])
            # 修改：使用format_creation_time格式化创建时间
            formatted_time = format_creation_time(creation_time) if creation_time else "未知"
            return images, search["deployment"], search["namespace"], search["suffix"], formatted_time

    return ["Not Found"], deployment, "Not Found", "", "未知"


def get_images_and_runtime_from_uat_batch(prom: PrometheusClient, deployments: list):
    """批量获取UAT环境镜像信息和创建时间"""
    results = {}

    if not deployments:
        return results

    # 使用线程池并行处理
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        future_to_dep = {}
        for dep in deployments:
            future = executor.submit(get_images_and_runtime_from_uat, prom, dep)
            future_to_dep[future] = dep

        for future in concurrent.futures.as_completed(future_to_dep):
            dep = future_to_dep[future]
            try:
                images, actual_dep, namespace, suffix, creation_time = future.result()
                results[dep] = {
                    "images": images,
                    "deployment": actual_dep,
                    "namespace": namespace,
                    "suffix": suffix,
                    "runtime": creation_time  # 修改：这里存储的是格式化后的创建时间
                }
            except Exception as e:
                print(f"Error processing {dep}: {e}")
                results[dep] = {"images": ["Not Found"], "runtime": "未知"}

    return results


def calculate_runtime(creation_timestamp):
    """计算运行时间（保留函数但不再使用）"""
    if not creation_timestamp:
        return "未知"

    current_time = time.time()
    runtime_seconds = current_time - creation_timestamp

    # 转换为天、小时、分钟
    days = int(runtime_seconds // (24 * 3600))
    hours = int((runtime_seconds % (24 * 3600)) // 3600)
    minutes = int((runtime_seconds % 3600) // 60)

    if days > 0:
        return f"{days}天{hours}小时"
    elif hours > 0:
        return f"{hours}小时{minutes}分钟"
    else:
        return f"{minutes}分钟"


def compare_images(images1, images2):
    """比较两个镜像列表是否相同"""
    return set(images1) == set(images2)